<?php
class CategoriesController extends AppController {
    var $name = 'Categories';

    var $pageTitle = 'Category Description';

    var $viewPath = 'its/inventories/categories';

    var $uses = array('Category', 'Product');

    /**
     * กำหนดค่าเริ่มต้นการแบ่งหน้าให้เรียงลำดับตาม รหัส category
     * @var array
     */
    var $paginate = array(
        'order' => array(
            'Category.code' => 'asc'
        )
    );

    function beforeFilter() {
        parent::beforeFilter();
        // ใช้ใน Tab menus element ระบุ Secondary controller ที่กำลังถูกเลือก
        $this->set('parentNav', 'its_admins');
        $this->set('tabMenu', 'tabmenus/its/admins');
    }

    function display() {
        parent::display();
        $this->_paging(Inflector::classify($this->name), 'LIKE');
    }

    function save() {
        $category_id = null;
        if (!empty($this->data)) {
            $this->data['Category']['code'] = strtoupper($this->data['Category']['code']);      // รหัสเก็บเป็นพิมพ์ใหญ่เสมอ
            $this->data['Category']['collector_id'] = $this->Auth->user('id');
            if($this->Category->save($this->data)) {
                $this->Session->setFlash("Category code {$this->data['Category']['code']} save succesfull.", 'flash/ok');
                $category_id = $this->Category->id;
            } else {
                $this->Session->setFlash("Category save fail.", 'flash/fail');
                // ถ้าเป็น mode edit เก็บ id เอาไว้กรณีบันทึกข้อมูลผิด
                $category_id = $this->data['Category']['id'];
            }
        }
        $this->setAction('view', $category_id);
    }

    function view($id = null) {
        // edit
        if ($id != null) {
            $this->data = $this->Category->findById($id);
            $this->Category->id = $id;
            $this->set('neighbors', $this->Category->find('neighbors', array('fields' => array('id', 'name'))));
            $this->set('mode', 'edit');
        } else {
            $this->set('mode', 'add');
        }

        $this->render('view');
    }

    function delete($id = null) {
        $is_success = false;

        // ถ้ายังไม่มี Product ไหน ใช้ Category นี้ ลบได้
        if(!$this->Product->hasAny(array('category_id' => $id))) {
            $is_success = $this->Category->delete($id);
        }

        if ($is_success) {
            $this->Session->setFlash("Category delete succesfull.", 'flash/ok');
            $this->setAction('display');
        } else {
            $this->Session->setFlash("Can not delete this category.", 'flash/fail');
            $this->setAction('view', $id);
        }
    }

    function inplace_editor($field, $id) {
        parent::inplace_editor($this->Category, $field, $id);
    }
}
?>
